//
//  HXSendCommonNotifyViewController.m
//  KD
//
//  Created by ifly on 16/3/7.
//  Copyright © 2016年 ifly. All rights reserved.
//

#import "HXSendCommonNotifyViewController.h"
#import "HXUpDataImageModel.h"
#import "HXSelectedPersonViewController.h"
#import "AWPlaceholderTextView.h"

@interface HXSendCommonNotifyViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,HXSelectedPersonViewControllerDelegate>
@property (weak, nonatomic) IBOutlet UITextField *titleTextField;
@property (weak, nonatomic) IBOutlet UIView *selectedPersonView;
@property (weak, nonatomic) IBOutlet UILabel *selectedPersonLabel;
@property (weak, nonatomic) IBOutlet UIView *contentView;
@property (weak, nonatomic) IBOutlet UIButton *imageOneBtn;
@property (weak, nonatomic) IBOutlet UIButton *imageTwoBtn;
@property(nonatomic,assign) NSInteger imageBtnTag;
@property(nonatomic,strong) NSMutableArray *pictArray;
@property(nonatomic,strong)NSMutableDictionary *dataDict;
@property(nonatomic,weak) AWPlaceholderTextView *placeholderTextView;
@property(nonatomic,strong) UIToolbar  *keyboardDoneButtonBar;
@property (weak, nonatomic) IBOutlet UITextField *dateTextField;
@property(nonatomic,strong) NSMutableArray<NSDictionary *> *userIdListArray;
@property(nonatomic,strong) UIDatePicker *datePicker;
@end

@implementation HXSendCommonNotifyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"发送预警通知";
    [self setUpBarBtn];
    AWPlaceholderTextView *textView = [[AWPlaceholderTextView alloc]init];
    [self.contentView addSubview:textView];
    self.placeholderTextView = textView;
    textView.placehoder = @"请输入内容....";
    textView.placehoderColor = [UIColor lightGrayColor];
    textView.frame = CGRectMake(10, 0, self.contentView.width, self.contentView.height);
    [self.imageOneBtn setBackgroundImage:[UIImage imageNamed:@"addimageshadow"] forState:UIControlStateNormal];
    [self.imageTwoBtn setBackgroundImage:[UIImage imageNamed:@"addimageshadow"] forState:UIControlStateNormal];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]init];
    self.selectedPersonView.userInteractionEnabled = YES;
    [self.selectedPersonView addGestureRecognizer:tap];
    [tap addTarget:self action:@selector(selectedPerson)];
    self.titleTextField.inputAccessoryView = self.keyboardDoneButtonBar;
    self.placeholderTextView.inputAccessoryView = self.keyboardDoneButtonBar;
    
    UILongPressGestureRecognizer *onelongPress=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(oneBtnlongPressClick:)];
    onelongPress.minimumPressDuration = 1;//长按时间
    onelongPress.allowableMovement = 22;//手指抖动范围
    [self.imageOneBtn addGestureRecognizer:onelongPress];
    
    UILongPressGestureRecognizer *twolongPress=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(twoBtnlongPressClick:)];
    twolongPress.minimumPressDuration = 1;//长按时间
    twolongPress.allowableMovement = 22;//手指抖动范围
    [self.imageTwoBtn addGestureRecognizer:twolongPress];
    
    
    UIDatePicker *beginPick = [[UIDatePicker alloc]init];
    beginPick.minimumDate = [NSDate date];
    self.datePicker = beginPick;
    //设置只显示日期
    beginPick.datePickerMode = UIDatePickerModeDateAndTime;
    //设置文字
    beginPick.locale = [[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"];
    self.dateTextField.inputView = beginPick;
    self.dateTextField.inputAccessoryView = self.keyboardDoneButtonBar;
    [beginPick addTarget:self action:@selector(endTimeAction:) forControlEvents:UIControlEventValueChanged];

}

-(void)endTimeAction:(UIDatePicker *)picker{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSTimeZone* sourceTimeZone = [NSTimeZone systemTimeZone];
    dateFormatter.timeZone = sourceTimeZone;
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSString *str = [dateFormatter stringFromDate: self.datePicker.date];
    self.dateTextField.text = str;
}

-(void)setUpBarBtn{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    button.size = CGSizeMake(70, 30);
    button.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    [button setTitle:@"发布" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [button addTarget:self action:@selector(send) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button];
}

- (IBAction)imageOneBtnClick:(id)sender {
    UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
//    pickerImage.navigationController.navigation.
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        pickerImage.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:pickerImage.sourceType];
//        NSArray *temp_MediaTypes = [UIImagePickerController availableMediaTypesForSourceType:picker.sourceType];
//        picker.mediaTypes = temp_MediaTypes;
//        pickerImage.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    }
    pickerImage.delegate = self;
    pickerImage.allowsEditing = YES;
    [self presentViewController:pickerImage animated:YES completion:^{
        self.imageBtnTag = 1;
    }];
}

-(void)oneBtnlongPressClick:(UILongPressGestureRecognizer*)press
{
    if (press.state == UIGestureRecognizerStateEnded)return;
    NSMutableDictionary *dict = self.pictArray[0];
    if (![GlobalUtil isNilValue:[dict objectForKey:@"Files_Path"]]) {//字段不是空
        [dict setObject:@"" forKey:@"Files_Path"];
        [SVProgressHUD showSuccessWithStatus:@"已删除"];
    }
    [self.imageOneBtn setBackgroundImage:[UIImage imageNamed:@"addimageshadow"] forState:UIControlStateNormal];
}
- (IBAction)imageTwoBtnClick:(id)sender {
    UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
//    [pickerImage.navigationController.navigationBar setBackgroundColor:MAINCOLOR];
//    UIButton *btn = [UIButton buttonWithType:UIButtonTypeContactAdd];
//    [btn setFrame:CGRectMake(0, 0, 88, 8)];
//    [pickerImage.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc]initWithCustomView:btn]];
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        pickerImage.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:pickerImage.sourceType];
    }
    pickerImage.delegate = self;
    pickerImage.allowsEditing = YES;
    [self presentViewController:pickerImage animated:YES completion:^{
        self.imageBtnTag = 2;
    }];
}
//
//-(void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
//    [[UIApplication  sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
//}
//-(void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
//    [[UIApplication  sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
//}
-(void)twoBtnlongPressClick:(UILongPressGestureRecognizer*)press
{
    if (press.state == UIGestureRecognizerStateEnded)return;
    NSMutableDictionary *dict = self.pictArray[1];
    if (![GlobalUtil isNilValue:[dict objectForKey:@"Files_Path"]]) {//字段不是空
        [dict setObject:@"" forKey:@"Files_Path"];
        [SVProgressHUD showSuccessWithStatus:@"已删除"];
    }
    [self.imageTwoBtn setBackgroundImage:[UIImage imageNamed:@"addimageshadow"] forState:UIControlStateNormal];
}




- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *originalImage =  (UIImage *) [info objectForKey:UIImagePickerControllerEditedImage];
    if(!originalImage){
        originalImage = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    [self setUpIconBtnWithImage:originalImage];
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
}

-(UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
    //    UIGraphicsBeginImageContext(size);
    //    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
    //    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    //    UIGraphicsEndImageContext();
    //    return scaledImage;
    
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    //Determine whether the screen is retina
    if([[UIScreen mainScreen] scale] == 2.0){                UIGraphicsBeginImageContextWithOptions(size, NO, 2.0);
    }else{
        UIGraphicsBeginImageContext(size);
    }
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    // 返回新的改变大小后的图片
    return scaledImage;
}

//选人
- (void)selectedPerson {
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"HXInform" bundle:nil];
    HXSelectedPersonViewController *vc = [sb instantiateViewControllerWithIdentifier:@"HXSelectedPersonViewController"];
    vc.delegate = self;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark - HXSelectedPersonViewControllerDelegate
- (void)getPersonMsg:(NSArray *)idArray nameArray:(NSArray *)nameArray{
    if (idArray.count == 0) return;
    if (nameArray.count == 0) return;
    for (NSString *str in idArray) {
        NSDictionary *dict = [NSDictionary dictionaryWithObject:str forKey:@"MU_UserID"];
        [self.userIdListArray addObject:dict];
    }
    NSString *name = [NSString string];
    for (NSString *str in nameArray) {
        name = [name stringByAppendingString:[str stringByAppendingString:@","]];
    }
    name = [name substringToIndex:(name.length - 1)];
    self.selectedPersonLabel.text = name;
    CGSize size = [self SizeWithString:self.selectedPersonLabel.text font:[UIFont systemFontOfSize:14]];
    [self.selectedPersonLabel setFrame:CGRectMake(0, 6, size.width, 25)];
    self.selectedPersonLabel.textColor = [UIColor blackColor];
}

//设置并上传图片
-(void)setUpIconBtnWithImage:(UIImage *)image{
    NSData *imageData = UIImageJPEGRepresentation(image, 1);
    if  (imageData.length>300000){
        UIImage *image = [UIImage imageWithData:imageData];
        imageData = UIImageJPEGRepresentation(image, 0.005);
    }
    //1。创建管理者对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObjectsFromArray:@[@"application/json", @"text/json",@"text/html", @"text/javascript", @"text/plain"]];
    [manager POST:[NSString stringWithFormat:@"%@/message/SendFiles.ashx",API_HOST] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:imageData name:@"img" fileName:@"name" mimeType:@"image/png"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        HXUpDataImageModel *dict = [[HXUpDataImageModel alloc]initWithDictionary:responseObject error:nil];
        if ([dict.code isEqualToString:@"200"]) {
            //            [self.superVc actionRefreshData];
            [SVProgressHUD showSuccessWithStatus:@"图上传成功"];
            if (self.imageBtnTag == 1) {
                NSMutableDictionary *mdict = self.pictArray[0];
                [mdict setObject:dict.FilePath forKey:@"Files_Path"];
                [self.imageOneBtn setBackgroundImage:image forState:UIControlStateNormal];
            }else if (self.imageBtnTag == 2){
                NSMutableDictionary *mdict = self.pictArray[1];
                [mdict setObject:dict.FilePath forKey:@"Files_Path"];
                [self.imageTwoBtn setBackgroundImage:image forState:UIControlStateNormal];
            }
        }else{
            [SVProgressHUD showErrorWithStatus:@"图上传失败"];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD showErrorWithStatus:@"图上传失败"];
    }];

}

-(void)send{
    
    if (![[UserDefaultHandler getUserDetault:kID] boolValue]) {
        [SVProgressHUD showErrorWithStatus:@"请登录"];
        return;
    }
//    if (self.pictArray.count!=2) {
//        [SVProgressHUD showErrorWithStatus:@"请上传图片"];
//        return;
//    }
    if ([self.placeholderTextView.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"请输入内容"];
        return;
    }
    if ([self.titleTextField.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"请输入标题"];
        return;
    }
    if (self.userIdListArray.count==0) {
        [SVProgressHUD showErrorWithStatus:@"请选择发送人员"];
        return;
    }
    if ([self.dateTextField.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"请选择预警时间"];
        return;
    }
    [self.dataDict setObject:self.dateTextField.text forKey:@"Mess_OpenDate"];
    [self.dataDict setObject:self.titleTextField.text forKey:@"Mess_Title"];
    [self.dataDict setObject:self.placeholderTextView.text forKey:@"Mess_Content"];
    [self.dataDict setObject:@"2" forKey:@"Mess_Type"];
    [self.dataDict setObject:@"true" forKey:@"Mess_IsSend"];
    [self.dataDict setObject:[UserDefaultHandler getUserDetault:kID] forKey:@"Mess_UserID"];
    [self.dataDict setObject:@"" forKey:@"Mess_EndDate"];
    [self.dataDict setObject:@"" forKey:@"Mess_Add"];
    [self.dataDict setObject:@"" forKey:@"Mess_X"];
    [self.dataDict setObject:@"" forKey:@"Mess_Y"];
    NSMutableArray *mArray = [[NSMutableArray alloc]init];
    for (NSMutableDictionary *mdict in self.pictArray) {
        if (![GlobalUtil isNilValue:[mdict objectForKey:@"Files_Path"]]) {
            [mArray addObject:mdict];
        }
    }
    [self.dataDict setObject:mArray forKey:@"picList"];
    [self.dataDict setObject:self.userIdListArray forKey:@"useridlist"];
    [self.dataDict setObject:[[NSArray alloc]init] forKey:@"questList"];
    
    [SVProgressHUD showWithStatus:@"正在发送" ];
    [NetworkAPI sendNotifyWithDict:self.dataDict
                           success:^(HXBaseModel *result) {
                               [SVProgressHUD dismiss];
                               if ([result.code isEqualToString:@"200"]) {
                                   [self.superVc actionRefreshData];
                                   [SVProgressHUD showSuccessWithStatus:@"发送成功"];
                                   [self.navigationController popViewControllerAnimated:YES];
                               }else{
                                   [SVProgressHUD showErrorWithStatus:@"网络错误"];
                               }
                           }failure:^(NSError *err) {
                               [SVProgressHUD showErrorWithStatus:@"网络错误"];
                           }];
}

-(CGSize)SizeWithString:(NSString*)str font:(UIFont *)font{
    NSDictionary *dict = @{NSFontAttributeName:font};
    CGSize maxSize = CGSizeMake(MAXFLOAT, 26);
    CGSize size = [str boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
    return size;
}
- (NSMutableArray *)pictArray{
    if (_pictArray == nil) {
        _pictArray  = [[NSMutableArray alloc]init];
        for (int i = 0; i<2; i++) {
            NSMutableDictionary *pictDict = [[NSMutableDictionary alloc]init];
            [pictDict setObject:@"imageName" forKey:@"Files_Name"];
            [pictDict setObject:@"" forKey:@"Files_Path"];
            [_pictArray addObject:pictDict];
        }
    }
    return _pictArray;
}
- (NSMutableDictionary *)dataDict{
    if (_dataDict == nil) {
        _dataDict  = [[NSMutableDictionary alloc]init];
    }
    return _dataDict;
}
-(NSMutableArray<NSDictionary *> *)userIdListArray{
    if (!_userIdListArray) {
        _userIdListArray = [[NSMutableArray alloc]init];
    }
    return _userIdListArray;
}
-(UIToolbar*)keyboardDoneButtonBar{
    if(!_keyboardDoneButtonBar){
        _keyboardDoneButtonBar= [[UIToolbar alloc] init];
        _keyboardDoneButtonBar.barStyle = UIBarStyleDefault;
        _keyboardDoneButtonBar.tintColor = nil;
        [_keyboardDoneButtonBar sizeToFit];
        UIBarButtonItem *flexItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                                  target:nil
                                                                                  action:nil];
        UIButton *okBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [okBtn addTarget:self action:@selector(DoneClicked:) forControlEvents:UIControlEventTouchUpInside];
        okBtn.size = CGSizeMake(44, 44);
        [okBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [okBtn setTitle:@"确定" forState:UIControlStateNormal];
        okBtn.titleLabel.textColor = [UIColor blueColor];
        UIBarButtonItem* doneButton = [[UIBarButtonItem alloc] initWithCustomView:okBtn];
        [_keyboardDoneButtonBar setItems:[NSArray arrayWithObjects:flexItem,doneButton, nil]];
        
    }
    return _keyboardDoneButtonBar;
}
-(void)DoneClicked:(UIButton *)btn{
    
    [self.view endEditing:YES];
}

@end
